/*
 * @Descripttion: 
 * @version: 
 * @Author: 刘冰见
 * @Date: 2024-10-09 08:52:19
 * @LastEditors: 刘冰见
 * @LastEditTime: 2024-10-12 13:29:47
 */
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get_storage/get_storage.dart';
import 'package:sousuoapp/net/response/base_response.dart';

///日志拦截器
class CustomInterceptor extends Interceptor {
  // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6IjE4MDY5Nzk4MDg0IiwiYXZhdGFyIjoiaHR0cDovL2t0Y3VvenJlZi5kZS9icGhqIiwiZXhwIjoxNzIwOTI1OTQzfQ.jj_Ts6txcwTnHQbMstTQWggjCPEcO2xy87nHlS4zDcM';
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final apiKey = GetStorage().read('token');
    print(apiKey);
    // 请求头 设置token
    options.headers['token'] = '$apiKey';

    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    //返回自定义的Base
    final baseResponse = BaseResponse(
        code: response.statusCode,
        msg: response.statusMessage,
        data: response.data);
    response.data = baseResponse;

    return handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    //处理错误信息
    handlerError(err);
    return handler.next(err);
  }

  ///处理错误信息 --自行去实现里面的功能代码
  void handlerError(DioException err) {
    switch (err.type) {
      //连接超时
      case DioExceptionType.connectionTimeout:
        EasyLoading.dismiss();
        break;
      //响应超时
      case DioExceptionType.receiveTimeout:
        EasyLoading.dismiss();
        break;
      //发送超时
      case DioExceptionType.sendTimeout:
        EasyLoading.dismiss();
        EasyLoading.showToast('系统错误');
        break;
      //请求取消
      case DioExceptionType.cancel:
        EasyLoading.dismiss();
        EasyLoading.showToast('系统错误');
        break;
      //错误响应 404 等
      case DioExceptionType.badResponse:
        EasyLoading.dismiss();
        EasyLoading.showToast('系统错误');
        break;
      //错误证书
      case DioExceptionType.badCertificate:
        EasyLoading.dismiss();
        EasyLoading.showToast('系统错误');
        break;
      //未知错误
      default:
        EasyLoading.dismiss();
        EasyLoading.showToast('系统错误');
        break;
    }
  }

  void printDebugLog(StringBuffer buffer) {
    if (kDebugMode) {}
  }
}
